package com.pz.gulimall.product.service.impl;

import com.pz.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.pz.gulimall.product.dao.AttrDao;
import com.pz.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.pz.gulimall.product.entity.AttrEntity;
import com.pz.gulimall.product.entity.CategoryEntity;
import com.pz.gulimall.product.vo.res.AttrGroupWithAttrsResVo;
import com.pz.gulimall.product.vo.res.SpuItemAttrGroup;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pz.gulimall.common.utils.PageUtils;
import com.pz.gulimall.common.utils.Query;

import com.pz.gulimall.product.dao.AttrGroupDao;
import com.pz.gulimall.product.entity.AttrGroupEntity;
import com.pz.gulimall.product.service.AttrGroupService;

import javax.annotation.Resource;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {
    @Resource
    private CategoryServiceImpl categoryService;
    @Resource
    private AttrAttrgroupRelationDao attrGroupRelationDao;
    @Resource
    private AttrDao attrDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 获取 当前分类下 所有分组 和 关联属性
     * @param catelogId
     * @return
     */
    @Override
    public List<AttrGroupWithAttrsResVo> getAttrGroupWithAttrByCatId(Long catelogId) {
        List<AttrGroupEntity> attrGroupEntities = this.list(new QueryWrapper<AttrGroupEntity>()
                .eq("catelog_id", catelogId));
        List<AttrGroupWithAttrsResVo> ans = attrGroupEntities.stream().map(item -> {
            AttrGroupWithAttrsResVo vo = new AttrGroupWithAttrsResVo();
            BeanUtils.copyProperties(item, vo);
            List<Long> existAttrId = attrGroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_group_id", vo.getAttrGroupId())).stream().map(attr->{
                        return attr.getAttrId();
            }).collect(Collectors.toList());
            if(existAttrId!=null && existAttrId.size()>0){
                List<AttrEntity> attrEntities = attrDao.selectBatchIds(existAttrId);
                vo.setAttrs(attrEntities);
            }
            return vo;
        }).collect(Collectors.toList());
        return ans;
    }

    public PageUtils queryPage(Map<String, Object> params, Long catelogId) {
        QueryWrapper<AttrGroupEntity> queryWrapper = new QueryWrapper<>();
        if(catelogId != 0){
            queryWrapper.eq("catelog_id", catelogId);
        }
        String key = (String) params.get("key");
        if(key!=null && !key.isEmpty()){
            //SELECT * FROM pms_attr_group WHERE (catelog_id = ? or attr_group_id = ?)

            queryWrapper.and((obj)->{
                //组名模糊搜索
                if(key.matches("[0-9]*$")){
                    obj.eq("attr_group_id",Long.valueOf(key));
                }else {
                    obj.or().like("attr_group_name",key);
                }
            });

        }
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }


    public AttrGroupEntity getAttrAndCatePathById(Long attrGroupId){
        AttrGroupEntity attrGroup = getById(attrGroupId);
        attrGroup.setCateLogIdPath(findCatelogIdPath(attrGroup.getCatelogId()));
        return attrGroup;
    }

    public Long[] findCatelogIdPath(Long catelogId){
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findCatelogIdPath(catelogId, paths);
        Long[] res = new Long[parentPath.size()];
        for (int i = 0; i < parentPath.size(); i++) {
            res[i] = parentPath.get(parentPath.size()-1-i);
        }
        return res;
    }

    /**
     *  递归找路径
     * @param catelogId
     * @param paths  搜集路径
     * @return
     */
    private List<Long> findCatelogIdPath(Long catelogId, List<Long> paths){
        paths.add(catelogId);
        CategoryEntity category = categoryService.getById(catelogId);
        if(category.getParentCid() != 0){
            findCatelogIdPath(category.getParentCid(), paths);
        }
        return paths;
    }

    /**
     * 查找一个商品的基本属性
     *
     * @param catalogId
     * @param spuId
     * @return
     */
    @Override
    public List<SpuItemAttrGroup> getProductBaseAttr(Long catalogId, Long spuId) {
        return this.baseMapper.queryBaseAttr(catalogId, spuId);
    }

}